<template>
  <div class="region-box">
    <div class="region-left">
      <div>
        <div>
          <p>访问数据</p>
          <ExclamationCircleOutlined/>
        </div>
        <div>
          <LineEchart/>
        </div>
        <p>日访问量</p>
      </div>
      <div>
        <div>
          <h1>视频（最多9个,限制mp4）</h1>
          <a-upload
              v-model:file-list="fileList"
              name="file"
              accept=".mp4"
              :action="BASE_UPLOAD_FILE"
              @change="handleChange"
          >
            <div v-if="fileList.length<9">
              <a-button>
                <UploadOutlined/>
                上传附件
              </a-button>
            </div>
          </a-upload>
        </div>
        <div>
          <h1>封面（最多9张）</h1>
          <a-upload
              accept="image/*"
              v-model:file-list="coverList"
              :action="BASE_UPLOAD_FILE"
              list-type="picture-card"
              @preview="handlePreview"
          >
            <div v-if="coverList.length < 9">
              <PlusOutlined/>
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </div>
      </div>
    </div>
    <div class="region-right">
      <div>
        <h1>地方简介</h1>
        <WangEdit :value-html="valueHtml" :content="detailData?.content??null"
                  @set-value-html="(v:string)=>valueHtml = v"/>
        <div style="margin: 30px auto;width: 60px">
          <a-button type="primary" @click="saveCLick">保存</a-button>
        </div>
      </div>
      <div class="region-right-title">
        <div>
          <h1>文献管理</h1>
          <p @click="addRelation('关联文献')">添加关联文献</p>
        </div>
        <RegionTable :data="literatureData"
                     :meta="literatureMeta"
                     @on-meta-change="(page:number,size:number)=>onLiteratureMeta(page,size)"
                     :is-relation="false"
                     :dict-id="route.params.id"
                     :is-article="false"/>
      </div>
      <div class="region-right-title">
        <div>
          <h1>文章管理</h1>
          <p @click="addRelation('关联文章')">添加关联文章</p>
        </div>
        <RegionTable :data="articleData"
                     :meta="articleMeta"
                     :dict-id="route.params.id"
                     @on-meta-change="(page:number,size:number)=>onArticleMeta(page,size)"
                     :is-relation="false"
                     :is-article="true"/>
      </div>
    </div>
    <!--  预览图片  -->
    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
    <!-- 关联的文章或文献 -->
    <a-modal :visible="relationModal" :title="relationTitle" @cancel="relationCancel">
      <RegionTable :data="relationData"
                   :meta="relationMeta"
                   :dict-id="route.params.id"
                   @on-meta-change="(page:number,size:number)=>onRelationMeta(page,size)"
                   :is-relation="true"
                   :is-article="relationTitle==='关联文章'"/>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import LineEchart from "@/components/LineEchart.vue";
import {PlusOutlined, UploadOutlined} from '@ant-design/icons-vue';
import {BASE_UPLOAD_FILE} from "@/axios";
import {onMounted, reactive, ref, watch, watchEffect} from "vue";
import {message, UploadChangeParam, UploadProps} from "ant-design-vue";
import {getBase64} from "@/util";
import WangEdit from "@/components/WangEdit.vue";
import type {ArticleDataType, LiteratureDataType, MetaType, RegionType} from "@/util/publicType";
import {useRoute} from "vue-router";
import {regionDetail, relationArticleList, relationLiteratureList, updateRegion} from "@/api/api";
import type {AxiosResponse} from "axios";
import RegionTable from "@/components/RegionTable.vue";
import {PageAdnSizeType} from "@/util/publicType";

// 附件list
const fileList = ref<any>([]);
// 封面list
const coverList = ref<any>([]);
// 是否预览
const previewVisible = ref(false);
// 预览地址
const previewImage = ref('');
// 预览标题
const previewTitle = ref('');
// 编辑器内容
const valueHtml = ref<string>("");
// 路由信息
const route = useRoute();
// 关联文献列表
const literatureData = ref<Array<LiteratureDataType>>([]);
// 文献分页数据
let literatureMeta = reactive<MetaType>({
  currentPage: 1,
  lastPage: 1,
  perSize: 1,
  total: 1
})
// 关联文章列表
const articleData = ref<Array<ArticleDataType>>([]);

// 文章分页数据
let articleMeta = reactive<MetaType>({
  currentPage: 1,
  lastPage: 1,
  perSize: 1,
  total: 1
})

// 关联项数据
let relationData = ref<Array<ArticleDataType | LiteratureDataType>>([]);

// 关联分页数据
let relationMeta = reactive<MetaType>({
  currentPage: 1,
  lastPage: 1,
  perSize: 15,
  total: 1
})

// 添加关联弹窗
const relationModal = ref<boolean>(false);
const relationTitle = ref<string>("");

// 区域详情
const detailData = ref<RegionType>({
  id: '',
  name: '',
  videos: [],
  images: [],
  category_id: '',
  content: ''
});

// 文献关联分页数据
const literaturePageAndSize = reactive<PageAdnSizeType>({
  page: 1,
  size: 15,
});

//文章关联分页数据
const articlePageAndSize = reactive<PageAdnSizeType>({
  page: 1,
  size: 15,
});

// 文章搜索name字段
const articleName = ref<string | null>(null);

// 文献搜索字段
const literatureName = ref<string | null>(null);

// 加载文件
const setFileData = (data: Array<{ id: string, path: string, type: string }>) => {
  return data.map(v => {
    return {
      uid: v?.id,
      status: 'done',
      name: v?.type,
      url: v?.path
    };
  })
}

// 区域详情
const getDetail = () => {
  regionDetail((route.params.id as string)).then((r: AxiosResponse) => {
    const data: RegionType = r.data.data.data;
    let videosList: any[] = [];
    let imagesList: any[] = [];
    videosList = setFileData(data.videos);
    imagesList = setFileData(data.images);
    coverList.value = imagesList;
    fileList.value = videosList;
    detailData.value = data;
  }, err => message.error(err))
}

// 字段重新赋值
const setRqData = (data: ArticleDataType[] | LiteratureDataType[]): ArticleDataType[] | LiteratureDataType[] => {
  return data.map(v => {
    return {
      ...v,
      key: v.id,
      dictName: v.dict.name
    }
  }) as (ArticleDataType[] | LiteratureDataType[])
}

// 请求文献
const getLiteratureData = (page: number, size: number, name: string | null = null, regionId: number | null = null) => {
  relationLiteratureList((route.params.id as string), page, size, name, regionId).then((r: AxiosResponse) => {
    let {data, meta} = r.data.data;
    if (regionId !== 0) {
      literatureMeta = Object.assign(literatureMeta, meta);
      literatureData.value = setRqData(data) as LiteratureDataType[];
    } else {
      relationMeta = Object.assign(relationMeta, meta);
      relationData.value = setRqData(data) as LiteratureDataType[];
    }
  }, err => message.error(err))
}

// 请求文章
const getArticleData = (page: number, size: number, name: string | null = null, regionId: number | null = null) => {
  relationArticleList((route.params.id as string), page, size, name, regionId).then((r: AxiosResponse) => {
    let {data, meta} = r.data.data;
    if (regionId !== 0) {
      articleMeta = Object.assign(articleMeta, meta);
      articleData.value = setRqData(data) as ArticleDataType[];
    } else {
      relationMeta = Object.assign(relationMeta, meta);
      relationData.value = setRqData(data) as ArticleDataType[];
    }

  }, err => message.error(err))
}

onMounted(() => {
  getDetail();
});

// // 文献变化时
// watchEffect(() => {
//   getArticleData(articlePageAndSize.page, articlePageAndSize.size, articleName.value);
// })
//
// // 文章变化时
// watchEffect(() => {
//   getLiteratureData(literaturePageAndSize.page, literaturePageAndSize.size, literatureName.value);
// });

// 取消预览
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

// 预览操作
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  // 转换格式
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  // 预览地址
  previewImage.value = file.url || file.preview;
  // 预览显示
  previewVisible.value = true;
  // 预览名字
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

// 上传附件
const handleChange = (info: UploadChangeParam) => {
  // 上传中
  if (info.file.status !== 'uploading') {
    // console.log(info.file, info.fileList);
  }
  // 上传成功
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 上传成功`);
  } else if (info.file.status === 'error') {
    // 上传失败
    // message.error(`${info.file.name} file upload failed.`);
  }
};

// 获取文件id
const getFileId = (data: any[]) => {
  return data.map(v => {
    return v?.response?.data?.data?.id ? v?.response?.data?.data?.id : v?.uid;
  })
}

// 保存
const saveCLick = () => {
  let videos: string[];
  let images: string[];
  videos = getFileId(fileList.value);
  images = getFileId(coverList.value);
  updateRegion(detailData.value.id, {images, videos, content: valueHtml.value}).then(() => {
    getDetail()
    message.success("更新成功");
  }, err => message.error(err))
}

// 文献表格分页变化时
const onLiteratureMeta = (page: number, size: number) => {
  literaturePageAndSize.page = page;
  literaturePageAndSize.size = size;
}

// 文章表格分页变化时
const onArticleMeta = (page: number, size: number) => {
  articlePageAndSize.page = page;
  articlePageAndSize.size = size;
}

// 关联表格分页变化时
const onRelationMeta = (page: number, size: number) => {
  relationMeta.currentPage = page;
  relationMeta.perSize = size;
  if (relationTitle.value === "关联文献") {
    getLiteratureData(page, size, literatureName.value, 0);
  } else {
    getArticleData(page, size, articleName.value, 0);
  }
}

const addRelation = (title: string) => {
  relationModal.value = true;
  relationTitle.value = title;
  if (title === "关联文献") {
    getLiteratureData(relationMeta.currentPage, relationMeta.perSize, literatureName.value, 0);
  } else {
    getArticleData(relationMeta.currentPage, relationMeta.perSize, articleName.value, 0);
  }
}

// 取消关联
const relationCancel = () => {
  relationModal.value = false;
  relationMeta.currentPage = 1;
  relationMeta.perSize = 15;
}


</script>
<style scoped lang="less">
.region-box {
  width: 100%;
  padding: 30px 0;
  display: flex;

  .region-left {
    flex: 1;
    margin-right: 30px;
  }

  .region-right {
    flex: 3;
    background: #eee;
    padding: 0 10px;
  }
}

.region-left > div:first-of-type {
  padding: 0 10px;
  width: 100%;
  background: #eee;
  height: 200px;

  > div:first-of-type {
    display: flex;
    align-items: center;
    justify-content: space-between;

    > p {
      margin: 10px 0;
      font-size: 16px;
      color: #000;
    }
  }

  > div:last-of-type {
    height: 100px;
    border-bottom: 1px solid #ddd;
  }

  > p {
    margin: 16px 0;
  }
}

.region-left > div:last-of-type {
  margin-top: 30px;
  width: 100%;
  background: #eee;
  padding: 10px 10px;

  > div h1 {
    font-size: 17px;
    color: #000;
  }
}

.region-right {
  > .region-right-title > div:first-of-type {
    display: flex;
    align-items: center;

    > h1 {
      font-size: 18px;
      color: #000;
      flex: 1;
      font-weight: 700;
    }

    > p {
      color: #1890ff;
      flex: 1;
      text-align: right;
      font-size: 17px;
      cursor: pointer;
    }
  }
}
</style>